//
//  MessageListenerChannelSupport.swift
//  lsnetchatplugin
//
//  Created by yunxiwangluo on 2020/5/12.
//

import UIKit
import NIMSDK

enum ResultType: Int {
    //错误
    case error = -1;
    //接收到消息
    case receiveMessage = 105;
    //自定义消息
    case customMessage = 100;
    //被踢了
    case chatRoomBeKicked = 10300;
    //直播结束消息
    case sendLiveEndMessage = 401;
    //String类型信息回传
    case stringType = 999;
}


class MessageListenerChannelSupport: NSObject,FlutterPlugin,FlutterStreamHandler{
    
    static let sharedInstance = MessageListenerChannelSupport()
    
    var eventSink: FlutterEventSink?
    
    static func register(with registrar: FlutterPluginRegistrar) {
        
        let channel = FlutterEventChannel(name: "lsnetchatplugin_e", binaryMessenger: registrar.messenger())
        
        channel.setStreamHandler(self.sharedInstance);
  
    }
    
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        self.eventSink = events;
        return nil
    }
    
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
         return nil
    }
    
    func sendMessageToFlutter(messages: [NIMMessage]){
        
        var dicts = Array<[String:Any]>();
        
        for item in messages {
            
            var dict = [String:Any]()
            
            if(item.messageType == .text){
            
                dict["content"] = item.text
                dict["nicName"] = item.senderName
                dict["msgType"] = item.messageType.rawValue
                dicts.append(dict)
                
            }else if (item.messageType == .notification){
            //对通知类型的消息处理
                if let o = item.messageObject,o.isKind(of: NIMNotificationObject.self){
                    
                    let msgObjc = o as! NIMNotificationObject;
                    
                    //如果是聊天室的通知消息
                    if msgObjc.notificationType == .chatroom{
                        
                        let chatRoomNoticContent = msgObjc.content as! NIMChatroomNotificationContent
                        
                        let nickName = chatRoomNoticContent.source?.nick
                        let userid = chatRoomNoticContent.source?.userId
                        let type = chatRoomNoticContent.eventType
                        var content = "";
                        
                        switch type {
                        case .enter:
                            content = "进入直播间"
                            break
                        case .exit:
                            content = "离开直播间"
                            break
                        default:
                            content = ""
                            break
                        }
                        
                        dict["nicName"] = nickName
                        dict["content"] = content
                        dict["msgType"] = item.messageType.rawValue
                        dict["accid"] = userid;
                        dicts.append(dict)
                        
                    }
                }
            }else if (item.messageType == .custom){
                
                if let o = item.messageObject,o.isKind(of: NIMCustomObject.self){
                
                     let customobjc = o as! NIMCustomObject
                    
                    let lmAttachment: LMCustomAttachment = customobjc.attachment as! LMCustomAttachment;
                    
                    let content = lmAttachment.jsonString; 
                    
                    /*
                    退出直播：//"{\"key\":20,\"data\":{\"message\":\"401\"}}"
                    
                    自定义消息：//"{\"key\":100,\"data\":{\"message\":\"{\\n  \\\"data\\\": {\\n    \\\"memberId\\\": 0,\\n    \\\"coachId\\\": 75,\\n    \\\"headImage\\\": \\\"\\/Image\\/PlatformApp\\/Member\\/637229735120263955.png\\\",\\n    \\\"nickName\\\": \\\"信陵公子\\\",\\n    \\\"description\\\": \\\"测试\\\",\\n    \\\"gender\\\": 1,\\n    \\\"birth\\\": \\\"2020-03-20\\\",\\n    \\\"authState\\\": 1,\\n    \\\"isCoach\\\": 1,\\n    \\\"introduction\\\": \\\"测试一下看看\\\",\\n    \\\"showPic\\\": \\\"\\/Image\\/PlatformApp\\/Coach\\/637229734757229527.png,\\/Image\\/PlatformApp\\/Coach\\/637229734757241775.png,\\/Image\\/PlatformApp\\/Coach\\/637229734757253550.png,\\/Image\\/PlatformApp\\/Coach\\/637229734757261629.png\\\",\\n    \\\"tel\\\": \\\"18633799924\\\",\\n    \\\"accid\\\": \\\"testyyt_4292\\\",\\n    \\\"liveToken\\\": \\\"b1366b950afe80802ad08a7bab8c0d89\\\",\\n    \\\"mchMemberId\\\": 4564,\\n    \\\"isBind\\\": 1,\\n    \\\"linkTel\\\": null\\n  }\\n}\\n                  \"}}"
                    */
                    
                    if (lmAttachment.type == 20){
                        
                        dict["accid"] = item.from;
                        dict["content"] = content
                        dict["nicName"] = item.senderName;
                        dict["msgType"] = lmAttachment.type
                        dicts.append(dict)
                        
                    }else{
                    
                        dict["msgType"] = lmAttachment.type;
                        dict["content"] = content
                        dict["nicName"] = item.senderName;
                        dict["accid"] = item.from;
                        dicts.append(dict)
                        
                    }
                    
//                    self.eventSink?(self.createResult(type: .customMessage, data: dicts));
//
//                    return
                    
                }

            }
        }
        
        self.eventSink?(self.createResult(type: .receiveMessage, data: dicts));
    }
    
    
    func LoginStatusEventChannelToFlutter(des: String){
        
        self.eventSink?(self.createResult(type: .stringType, data: des));
    }
    
//    func ChatRoomLinkEventChannelToFlutter(des: String){
//
//        self.eventSink?(self.createResult(type: .stringType, data: des));
//    }
    
    func messageSendResultEventChannelToFlutter(des: String){
        
        self.eventSink?(self.createResult(type: .stringType, data: des));
    }
    
    
    func createResult(type:ResultType,data:Any?)->Dictionary<String, Any?>{
        
        return ["type":type.rawValue,"data":data]
        
    }
    
    //聊天室被踢相关的消息回传
    func chatRoomBeKicked(msgType: Int){
        
        var dicts = Array<[String:Any]>();
        var dict = [String:Any]()
        
        dict["nicName"] = "直播间消息"
        dict["content"] = ""
        dict["msgType"] = msgType
        
        dicts.append(dict)
        
        self.eventSink?(self.createResult(type: .chatRoomBeKicked, data:nil));
        
    }
    
    
    
}



